package cn.unknownerror.ueteam.listener;

import cn.unknownerror.ueteam.PluginUETeam;
import cn.unknownerror.ueteam.team.ITeam;
import cn.unknownerror.ueteam.team.NormalTeam;
import cn.unknownerror.ueteam.team.TeamAPI;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerExpChangeEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class PlayerActionListener implements Listener {
    @EventHandler
    public void onPlayerGainExp(PlayerExpChangeEvent event){
        ITeam team = TeamAPI.findTeamFromPlayer(event.getPlayer().getUniqueId());
        if(team==null) return;
        if(!(team instanceof NormalTeam)) return;
        double share = PluginUETeam.getInstance().getConfigurationManager().getConfig().getDouble("Team.Exp_Sharing.proportion",1);
        int amount = event.getAmount();
        int expshare = (int) ((1-share)*amount);
        Player p =event.getPlayer();
        Location center = p.getLocation();
        List<Player> nearby = new ArrayList<>();
        double radius = NormalTeam.getRadius();
        for(Entity entity: Objects.requireNonNull( center.getWorld() ).getNearbyEntities(center,radius,radius,radius)) {
            if (entity instanceof Player) {
                nearby.add((Player) entity);
            }
        }
        amount= (int) (amount*share);
        if(expshare <1) return;
        if(nearby.size()<=1) return;
        expshare=expshare/(nearby.size()-1);
        for(Player nb : nearby){
            if(nb.getUniqueId().equals(event.getPlayer().getUniqueId())) continue;
            nb.giveExp(expshare);
            nb.sendMessage("§a从玩家 §f"+p.getName()+" §a分享到§e"+expshare+"§a点经验");
        }
        event.setAmount(amount);
    }
}
